/**
 * @description  券池审批
 * @author shenhong
 */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { MinusCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { TreeSelect, Input, Tooltip } from 'antd';
import { TableC, SecuritiesCodeC, SelectC, codeType, InputNumberC, TreeSelectC } from '../../../../comps';
import style from './index.less';
import debounce from 'lodash/debounce';
import uuid from 'es6-uuid';
import config from '../../../../comps/business/tradingMarket/config';
import _ from 'lodash';

const FormItem = Form.Item;
@Form.create()
class ColRender extends PureComponent {
  constructor(props) {
    super(props);
    this.columns = [
      {
        title: (
          <span>
            <label className={style.lableRequire}></label>标的代码
          </span>
        ),
        dataIndex: 'code',
        key: 'code',
        visible: true,
      },
      {
        title: (
          <span>
            <label className={style.lableRequire}></label>标的简称
          </span>
        ),
        dataIndex: 'secuabbr',
        key: 'secuabbr',
        visible: true,
      },
      {
        title: (
          <span>
            <label className={style.lableRequire}></label>交易市场
          </span>
        ),
        dataIndex: 'market',
        key: 'market',
        visible: true,
      },
      {
        title: (
          <span>
            <label className={style.lableRequire}></label>发行主体
          </span>
        ),
        dataIndex: 'conpany',
        key: 'conpany',
        visible: true,
      },
      {
        title: '行业',
        dataIndex: 'industry',
        key: 'industry',
        visible: false,
      },
      {
        title: '研究员',
        dataIndex: 'researcher',
        key: 'researcher',
        visible: false,
      },
      {
        title: '可投资额度',
        dataIndex: 'investmentAmounts ',
        key: 'investmentAmounts',
        visible: false,
      },
      {
        title: '内部评级',
        dataIndex: 'internalRating ',
        key: 'internalRating',
        visible: false,
      },
      {
        title: '主体区域',
        dataIndex: 'bodyArea ',
        key: 'bodyArea',
        visible: false,
      },
      {
        title: '债券类型',
        dataIndex: 'bondType ',
        key: 'bondType',
        visible: false,
      },
      {
        title: '标签',
        dataIndex: 'title2',
        key: 'title2',
        visible: true,
      },
      {
        title: '操作',
        dataIndex: 'operation',
        key: 'operation',
        visible: true,
        render: (_, record) => {
          return this.props.type == 'see' || this.props.type == 'outPool2' ? null : (
            <div style={{ width: '45px', textAlign: 'center' }}>
              <a onClick={() => this.delete(record)}>
                <MinusCircleOutlined />
              </a>
            </div>
          );
        },
      },
    ];
    this.state = {
      value: undefined,
      rowData: [], // 新增的表格数据
      childData: [],
      rowData2: [], // 编辑查看时的表格数据
      childOne: {},
      isLength: true,
      colsNum: undefined, // 显示的列数
      teplataId: undefined,
      poolType: undefined, // 券池类型
      tagNames: '',
      tagIds: '',
      dataSource: [],
      template: true,
      page: {
        current: 1,
      },
      zqDataSource: [],
      direction: '', // 操作方向
      internalRatingData: [], // 内部评级下拉数据
    };
    this.researcherChange = debounce(this.researcherChange, 500);
  }

  componentDidMount() {
    const { defaultData, dispatch } = this.props;
    this.props.onRef(this);
    dispatch({
      type: 'couponPoolApprovalM/getInternalRating',
      payload: {
        tenant: localStorage.getItem('antd-pro-userId'),
      },
      callback: (res) => {
        if (res) {
          this.setState({
            internalRatingData: res,
          });
        }
      },
    });
    this.setState({
      dataSource: defaultData,
    });
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    if (nextProps.teplataId != this.state.teplataId) {
      this.setState({
        teplataId: nextProps.teplataId,
        dataSource: nextProps.uploadData,
        template: true,
      });
    }
    if (nextProps.poolType != this.state.poolType) {
      this.setState({
        poolType: nextProps.poolType,
      });
      if (nextProps.poolType == 'stock') {
        (this.columns[4].visible = true), (this.columns[5].visible = true);
      } else {
        (this.columns[4].visible = false), (this.columns[5].visible = false);
      }
      this.getZqData(nextProps.poolType);
    }
    if (nextProps.direction != this.state.direction) {
      this.setState({ direction: nextProps.direction });
      if (nextProps.direction == '1') {
        this.columns[6].visible = true;
      } else {
        this.columns[6].visible = false;
      }
    }
    if (nextProps.poolType != this.state.poolType || nextProps.direction != this.state.direction) {
      if (nextProps.poolType == 'bond' && nextProps.direction == '1') {
        this.columns[7].visible = true;
        this.columns[8].visible = true;
        this.columns[9].visible = true;
      } else {
        this.columns[7].visible = false;
        this.columns[8].visible = false;
        this.columns[9].visible = false;
      }
    }
  }

  // 获取标的代码组件初始化数据
  getZqData = (poolType) => {
    if (poolType) {
      let newType = '';
      if (poolType == 'bond') {
        newType = codeType.zq;
      } else if (poolType == 'fund') {
        newType = codeType.jj;
      } else if (poolType == 'stock') {
        newType = codeType.gp;
      }
      this.props.dispatch({
        type: 'securitiesCodeM/getSecuritiesList',
        payload: {
          codeType: newType,
          expiry: 1,
        },
        callback: (e) => {
          this.setState({
            zqDataSource: e,
          });
        },
      });
    }
  };

  // 删除行数据
  delete = (e) => {
    const arr = this.state.dataSource.filter((item) => item.id != e.id); // 匹配数据
    this.setState({
      dataSource: arr,
    });
  };

  // 券池名称改变时恢复标的信息数据
  changePoolName = () => {
    this.setState({
      dataSource: [],
    });
  };

  // 新增行
  addRow = () => {
    const { poolType, tagData } = this.props;
    const dataSource = this.state.dataSource || [];
    dataSource.unshift({
      id: uuid(32),
    });
    this.setState({
      dataSource: [...dataSource],
    });
  };

  // 标的证券改变事件
  handleChange = (e, record) => {
    const { defaultDataAll, poolType, dispatch, direction, securityId } = this.props;
    const { dataSource } = this.state;
    const arr = dataSource.filter((item) => item.id == record.id); // 匹配数据
    const index = dataSource.findIndex((item) => item.id == record.id); // 查找数据位置
    if (e) {
      if (e.tradingCode && e.exchangeCode) {
        arr[0].exchangeCode = e.exchangeCode;
        arr[0].tradingCode = e.tradingCode;
        if (poolType) {
          let newType = '';
          if (poolType == 'bond') {
            newType = codeType.zq;
          } else if (poolType == 'fund') {
            newType = codeType.jj;
          } else if (poolType == 'stock') {
            newType = codeType.gp;
          }

          dispatch({
            type: 'couponPoolApprovalM/getSecuritiesDetail',
            payload: {
              tradingCode: e.tradingCode,
              exchangeCode: e.exchangeCode,
              type: newType,
            },
            callback: (res) => {
              if (res) {
                (arr[0].secuabbr = res.secuabbr), // 标的简称
                  (arr[0].market = res.exchangeName), // 交易市场
                  (arr[0].conpany = res.issuer),
                  (arr[0].bodyArea = res.bodyArea), // 主体区域
                  (arr[0].bondType = res.bondType), // 债券类型
                  dataSource.splice(index, 1, arr[0]);
                this.setState(
                  {
                    dataSource,
                  },
                  () => {
                    if (poolType == 'stock') this.getIndustryAndRole(e, arr, index); // 查询行业和研究员
                  },
                );
              }
            },
          });
          if (direction == '2') {
            dispatch({
              type: 'couponPoolApprovalM/bringTag',
              payload: {
                tradingCode: e.tradingCode,
                exchangeCode: e.exchangeCode,
                securityId,
                flowNumber: defaultDataAll?.flowNumber,
              },
              callback: (res) => {
                if (res) {
                  this.setState({
                    tagNames: res.tagNames,
                    tagIds: res.tagIds,
                  });
                }
              },
            });
          }
        }
      }
    } else {
      arr[0].exchangeCode = undefined;
      arr[0].tradingCode = undefined;
      dataSource.splice(index, 1, arr[0]);
      this.setState({
        dataSource,
      });
    }
  };

  // 查询行业
  getIndustryAndRole = (e, arr, index) => {
    const { dispatch } = this.props;
    const { dataSource } = this.state;
    dispatch({
      type: 'couponPoolApprovalM/getIndustryAndRole',
      payload: {
        tradingCode: e.tradingCode,
        exchangeCode: e.exchangeCode,
      },
      callback: (res) => {
        if (res) {
          if (res.code == 0) {
            arr[0].industry = res.data?.dataSource?.industry;
            dataSource.splice(index, 1, arr[0]);
            this.setState({
              dataSource,
            });
          } else {
            arr[0].industry = '';
            dataSource.splice(index, 1, arr[0]);
            this.setState({
              dataSource,
            });
          }
        }
      },
    });
  };

  // 获取数据
  getData = () => {
    const { dataSource } = this.state;
    const { poolType, direction } = this.props;
    const resArr = [];

    for (const i of dataSource) {
      const newArr = {};
      newArr.exchangeCode = i.exchangeCode;
      newArr.tradingCode = i.tradingCode;
      newArr.tagId = i.title2 ? i.title2 : [];
      if (direction == '1') {
        newArr.investmentAmounts = i.investmentAmounts;
        newArr.bodyArea = i.bodyArea; // 主体区域
        newArr.bondType = i.bondType; // 债券类型
        newArr.internalRating = i.internalRating; // 内部评级
      }
      if (poolType == 'stock') {
        newArr.industry = i.industry;
        newArr.researcher = i.researcher;
      }
      resArr.push(newArr);
    }
    return resArr;
  };

  // 数组去重
  unique = (arr) => {
    return [...new Set(arr)];
  };

  handleChangeLabel = (value, label, extra, record) => {
    const { dataSource } = this.state;
    function getSelectedNode(data, currentValue = []) {
      const res = [];
      function getItem(arr) {
        arr.map((item) => {
          if (currentValue.includes(item.value)) {
            res.push(item);
          }
          if (item.children) getItem(item.children);
        });
        return res;
      }
      return getItem(data);
    }
    const { poolType, tagData } = this.props;
    const tags = poolType == 'bond' ? tagData.bondTag : poolType == 'fund' ? tagData.fundTag : tagData.stockTag;
    const newArr2 = getSelectedNode(tags, value);
    const newTag = [];
    if (newArr2?.length) {
      newArr2.map((item) => {
        newTag.push(item.value);
        if (item.pid !== null) {
          newTag.push(item.pid);
        }
      });
    }
    const newTag2 = this.unique(newTag);
    const arr = dataSource.filter((item) => item.id == record.id); // 匹配数据
    const index = dataSource.findIndex((item) => item.id == record.id); // 查找数据位置
    arr[0].title2 = newTag2;
    dataSource.splice(index, 1, arr[0]);
    this.setState({
      title2: newTag2,
      isChange: true,
      dataSource: _.cloneDeep(dataSource),
    });
  };

  researcherChange = (e, record, name) => {
    const { dataSource } = this.state;
    const arr = dataSource.filter((item) => item.id == record.id); // 匹配数据
    const index = dataSource.findIndex((item) => item.id == record.id); // 查找数据位置
    arr[0][name] = e;
    dataSource.splice(index, 1, arr[0]);
    this.setState({
      dataSource,
    });
  };

  // 响应投资额度变化事件
  investmentAmountsChange = (e, record) => {
    this.researcherChange(e, record, 'investmentAmounts');
  };

  // 改变columns
  changeColumns = (columns) => {
    const {
      form: { getFieldDecorator },
      type,
      tagData,
      researchers,
      poolType,
      isDisabled,
      toolText,
      direction,
      values,
    } = this.props;
    const { tagIds, tagNames, template, zqDataSource, internalRatingData } = this.state;
    const tags = poolType == 'bond' ? tagData.bondTag : poolType == 'fund' ? tagData.fundTag : tagData.stockTag;

    // 股票展示行业和研究员字段
    const arr = columns.filter((item) => item.visible == true);
    // 计算每列宽度
    const width = `${parseFloat(95 / (arr.length - 1))}%`;
    let newType = '';
    if (poolType == 'bond') {
      newType = codeType.zq;
    } else if (poolType == 'fund') {
      newType = codeType.jj;
    } else if (poolType == 'stock') {
      newType = codeType.gp;
    }
    arr.map((item) => {
      if (item.key == 'code') {
        (item.width = width),
          (item.render = (text, record) => {
            const findvalue = config.filter((item) => {
              return item.value == record.exchangeCode;
            });
            return (
              <SecuritiesCodeC
                form={this.props.form}
                initialValue={
                  type !== 'add' || template ? (record.exchangeCode && record.tradingCode ? `${record.tradingCode}-${record.secuabbr}-${findvalue[0]?.title}` : '') : ''
                }
                dataIndex={`code-${record.id}`}
                onChange={(e) => this.handleChange(e, record)}
                titleDisplay={false}
                codeType={newType}
                queryItems={{ expiry: 1 }}
                noQueryForInit={true}
                dsFromParent={zqDataSource ? zqDataSource : []}
                disabled={type == 'outPool2' ? true : isDisabled}
                rules={[{ required: true, message: ' ' }]}
              />
            );
          });
      }
      if (item.key == 'researcher') {
        // 研究员
        (item.width = width),
          (item.render = (text, record) => {
            return (
              <SelectC
                form={this.props.form}
                initialValue={(type !== 'add' || template) && record.researcher ? record.researcher : undefined}
                dataIndex={`researcher-${record.id}`}
                disabled={type == 'outPool2' ? false : isDisabled}
                dataSource={researchers ? researchers : []}
                onChange={(e) => this.researcherChange(e, record, 'researcher')}
              />
            );
          });
      }
      if (item.key == 'title2') {
        (item.width = width),
          (item.render = (text, record) => {
            return type !== 'outPool2' ? (
              <div>
                <TreeSelectC
                  dataIndex={`title2-${record.id}`}
                  form={this.props.form}
                  initialValue={direction == '2' ? tagIds : (type !== 'add' || template) && record.tag ? record.tag : []}
                  styleRow={{ width: 250 }}
                  dataSource={tags}
                  placeholder='请选择标签'
                  allowClear={true}
                  treeDefaultExpandAll={true}
                  maxTagCount={0}
                  isMultiple={true}
                  onChange={(value, label, extra) => this.handleChangeLabel(value, label, extra, record)}
                  disabled={values == 'manual' && direction == '2' ? true : isDisabled}
                  showSearch={true}
                />
              </div>
            ) : (
              <div>
                <TreeSelectC
                  dataIndex={`title2-${record.id}`}
                  form={this.props.form}
                  initialValue={(type !== 'add' || template) && record.tag ? record.tag : []}
                  styleRow={{ width: 250 }}
                  dataSource={tags}
                  placeholder='请选择标签'
                  allowClear={true}
                  treeDefaultExpandAll={true}
                  maxTagCount={0}
                  isMultiple={true}
                  onChange={(value, label, extra) => this.handleChangeLabel(value, label, extra, record)}
                  disabled={type == 'outPool2' ? true : isDisabled}
                />
              </div>
            );
          });
      }
      if (item.key == 'secuabbr') {
        (item.width = width),
          (item.render = (text, record) => {
            return (
              <div style={{ paddingBottom: '10px' }}>
                <Input style={{ width: '100%' }} value={record.secuabbr} disabled={true} />
              </div>
            );
          });
      }
      if (item.key == 'market') {
        (item.width = width),
          (item.render = (text, record) => {
            const findvalue = config.filter((item) => {
              return item.value == record.exchangeCode;
            });
            return (
              <div style={{ paddingBottom: '10px' }}>
                <Input style={{ width: '100%' }} value={findvalue[0]?.title} disabled={true} />
              </div>
            );
          });
      }
      if (item.key == 'conpany') {
        (item.width = width),
          (item.render = (text, record) => {
            return (
              <div style={{ paddingBottom: '10px' }}>
                <Input style={{ width: '100%' }} value={record.conpany} disabled={true} />
              </div>
            );
          });
      }
      if (item.key == 'industry') {
        (item.width = width),
          (item.render = (text, record) => {
            return (
              <div style={{ paddingBottom: '10px' }}>
                <Input style={{ width: '100%' }} value={record.industry} disabled={true} />
              </div>
            );
          });
      }

      if (item.key == 'investmentAmounts') {
        // 可投资额度
        (item.width = width),
          (item.render = (text, record) => {
            return (
              <div>
                <InputNumberC
                  form={this.props.form}
                  dataIndex={`investmentAmounts-${record.id}`}
                  initialValue={record.investmentAmounts}
                  style={{ width: '100%' }}
                  disabled={isDisabled}
                  splitStyle={true}
                  precision={2}
                  onChange={(e) => this.investmentAmountsChange(e, record)}
                />
              </div>
            );
          });
      }

      if (item.key == 'internalRating') {
        // 内部评级
        (item.width = width),
          (item.render = (text, record) => {
            return (
              <div>
                <SelectC
                  form={this.props.form}
                  initialValue={record.internalRating}
                  dataIndex={`internalRating-${record.id}`}
                  disabled={isDisabled}
                  dataSource={internalRatingData ? internalRatingData : []}
                  onChange={(e) => this.researcherChange(e, record, 'internalRating')}
                />
              </div>
            );
          });
      }
      if (item.key == 'bodyArea') {
        // 主体区域
        (item.width = width),
          (item.render = (text, record) => {
            return (
              <div style={{ paddingBottom: '10px' }}>
                <Input style={{ width: '100%' }} value={record.bodyArea} disabled={true} />
              </div>
            );
          });
      }
      if (item.key == 'bondType') {
        // 债券类型
        (item.width = width),
          (item.render = (text, record) => {
            return (
              <div style={{ paddingBottom: '10px' }}>
                <Input style={{ width: '100%' }} value={record.bondType} disabled={true} />
              </div>
            );
          });
      }
    });
    return arr;
  };

  // 表格分页
  handleTableChange = (current, pageSize) => {
    this.setState({
      page: {
        current,
      },
    });
  };

  render() {
    const { dataSource, page } = this.state;
    const { isError } = this.props;
    const newColumns = this.changeColumns(this.columns);
    return (
      <div className='renderbody'>
        <TableC columns={newColumns} dataSource={dataSource} rowKey='id' current={page.current} pageSizeOptions={['10']} pageSize={10} onPageChange={this.handleTableChange} />
        {isError ? <span style={{ color: 'red', marginLeft: '20px' }}>请填写完整的标的要素信息</span> : null}
      </div>
    );
  }
}

export default connect(({ couponPoolApprovalM, securitiesCodeM }) => ({ couponPoolApprovalM, securitiesCodeM }))(ColRender);
